package com.ze.java.datastructure.array;

import java.util.Arrays;
import java.util.Objects;

/**
 * @Author:yangzy
 * @Date:2021/6/3 16:27
 */
public class Array<T> {
    private T[] data;
    private int size;

    public Array(int capacity) {
        data = (T[]) new Object[capacity];
        size = 0;
    }

    public Array() {
        this(10);
    }

    public int getSize() {
        return size;
    }

    public int getCapacity() {
        return data.length;
    }

    public void addLast(T item) {
        add(size, item);
    }

    public void addFirst(T item) {
        add(0, item);
    }

    public boolean contains(T item) {
        for (int i = 0; i < size; i++) {
            if (Objects.equals(data[i], item)) {
                return true;
            }
        }
        return false;
    }

    public int find(T item) {
        for (int i = 0; i < size; i++) {
            if (Objects.equals(data[i], item)) {
                return i;
            }
        }
        return -1;
    }

    public void add(int index, T item) {
        if (data.length == size) {
            throw new IllegalArgumentException("Array is full");
        }
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("index error");
        }
        for (int i = size; i > index; i--) {
            data[i] = data[i - 1];
        }
        data[index] = item;
        size++;
    }

    public T removeFirst() {
        return remove(0);
    }


    public T remove(int index) {
        if (index < 0 || index >= size) {
            throw new IllegalArgumentException("index error");
        }
        T item = (T) data[index];
        for (int i = index; i < size - 1; i++) {
            data[i] = data[i + 1];
        }
        data[size - 1] = null;
        size--;
        return item;
    }

    @Override
    public String toString() {
        return "Array{" +
                "data=" + Arrays.toString(data) +
                ", size=" + size +
                '}';
    }

    public static void main(String[] args) {
        Array<Integer> array = new Array<>(20);
        for (int i = 0; i < 10; i++) {
            array.addLast(i);
        }
        System.out.println(array.toString());

        array.add(2, 100);
        System.out.println(array.toString());
        array.remove(9);
        System.out.println(array.toString());
    }
}
